package com.genius.Genius.Util.TestMaster;

/**
 * 1. Use lambda ()->{} to test method
 * 2. For a rule,use it in @Test
 */
public class TestMasterLog {

    private static String otherLine = "\n\n\n";
    public static final String LOG_MEMORY = "| Use Memory(B):%s | Max Memory(MB):%s | Total Memory(MB):%s | Free Memory(MB):%s |";
    public static final String LOG_TIME = "| Time(ms): %s |";

    public static void loopTestLog(TestFunction testFunction,int loop,boolean isLog){
        long sum = 0;
        for (int i = 0; i < loop ; i++) {
            if (isLog) {
                System.out.println("loop: "+i);
            }
            long startTime = System.currentTimeMillis();
            testFunction.test();
            long endTime = System.currentTimeMillis();
            sum = endTime-startTime;
        }
        log(String.format("|"+loop+" Avg Loop Time(ms): %s |",sum));
    }

    public static void logMemory(TestFunction testFunction){
        logMemory(testFunction,false);
    }

    public static void logMemory(TestFunction testFunction,boolean isGC){
        int MB = 1048576;
        long freeMemory =  Runtime.getRuntime().freeMemory();
        long totalMemory = Runtime.getRuntime().totalMemory()/MB;
        long maxMemory = Runtime.getRuntime().maxMemory();

        testFunction.test();

        long currentFreeMemory = Runtime.getRuntime().freeMemory();
        if (isGC) {
            Runtime.getRuntime().gc();
        }
        log(String.format(LOG_MEMORY,freeMemory-currentFreeMemory,maxMemory/MB,totalMemory,currentFreeMemory/MB));
    }

    public static void logThread(TestFunction testFunction){
        ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
        int total = Thread.activeCount();
        Thread[] threads = new Thread[total];
        threadGroup.enumerate(threads);
        testFunction.test();
        String threadLog = "| Thread%s:%s | State:%s | Priority:%s |";
        System.out.println("--------Thread List--------");
        for (Thread t:threads){
            System.out.println(String.format(threadLog,t.getId(),t.getName(),t.getState(),t.getPriority()));
        }
        System.out.println("---------------------------");
    }

    public static void logTime(TestFunction testFunction){
        long startTime = System.currentTimeMillis();
        testFunction.test();
        long endTime = System.currentTimeMillis();
        log(String.format(LOG_TIME,endTime - startTime));
    }

    private static void log(String message){
        System.out.println(message);
    }
}
